package com.wushi.lenovo.asia5b.app_ui.orderdetail;

import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mvp.base.BaseMvpFragment;
import com.mvp.base.BaseSimpleFragment;
import com.mvp.base.model.ResultModel;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.goods.mvpview.OrderDetailFragmentView;
import com.wushi.lenovo.asia5b.app_di.goods.presenter.OrderDetailFragmentPresenter;
import com.wushi.lenovo.asia5b.app_event.OrderReceiveEvent;
import com.wushi.lenovo.asia5b.app_model.credit.BaseHisModel;
import com.wushi.lenovo.asia5b.app_model.good.ChargesBean;
import com.wushi.lenovo.asia5b.app_model.good.OrderDetailModel;
import com.wushi.lenovo.asia5b.app_model.good.OrderParcelResModel;
import com.wushi.lenovo.asia5b.app_model.good.OrderTrackModel;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.OrderGoodBean;
import com.wushi.lenovo.asia5b.app_model.profile.AddressModel;
import com.wushi.lenovo.asia5b.app_ui.credit.fragment.DownPdfDF;
import com.wushi.lenovo.asia5b.app_ui.good.adapter.OrderCheckPriceAdapter;
import com.wushi.lenovo.asia5b.app_ui.good.adapter.OrderDetailGoodAdapter;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.DeliveryNoticeDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.InternationalNoticeDialog;
import com.wushi.lenovo.asia5b.app_utils.helper.CrashHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyuncai on 2020/3/12.
 */
public abstract class OrderDetailFragment extends BaseMvpFragment<OrderDetailFragmentView, OrderDetailFragmentPresenter>
        implements OrderDetailFragmentView {

    public static OrderDetailFragment newInstance(Context context) {
        return (OrderDetailFragment) Fragment.instantiate(context, OrderDetailFragment.class.getName(), null);
    }

    public int order_id;
    public OrderDetailModel model;
    public OrderDetailActivity orderDetailActivity;

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        orderDetailActivity = (OrderDetailActivity) mActivity;
        order_id = orderDetailActivity.order_id;
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView();

        initEvent();
    }

    @Override
    protected void lazyFetchData() {

        initData();

    }

    @Override
    protected void initView() {

    }

    protected void contactAddress(StringBuilder stringBuilder, AddressModel addressModel) {
        if (model != null && addressModel != null) {
            if (addressModel != null) {
                //姓名1
                if (!TextUtils.isEmpty(addressModel.getContact_name())) {
                    stringBuilder.append(addressModel.getContact_name());
                    stringBuilder.append("\n");
                }
                //地址2
                if (!TextUtils.isEmpty(addressModel.getLocalAddressDetail())) {
                    stringBuilder.append(addressModel.getLocalAddressDetail());
                    stringBuilder.append("\n");
                }
                //号码3
                if (!TextUtils.isEmpty(addressModel.getContact_no())) {
                    stringBuilder.append(addressModel.getContact_no());
                }
            } else {
                //姓名1
                if (!TextUtils.isEmpty(model.getPayment_name())) {
                    stringBuilder.append(model.getPayment_name());
                    stringBuilder.append("\n");
                }
                //地址2
                if (!TextUtils.isEmpty(model.getPaymentAddress())) {
                    stringBuilder.append(model.getPaymentAddress());
                    stringBuilder.append("\n");
                }
                //号码3
                if (!TextUtils.isEmpty(model.getPayment_mobile())) {
                    stringBuilder.append(model.getPayment_mobile());
                }
            }
        }

    }

    protected void setOrderDetailView() {

    }

    protected void setGoodsView(List<OrderGoodBean> order_parcel, RecyclerView rv_orderdetail_goods) {
        if (order_parcel != null && order_parcel.size() != 0) {
            rv_orderdetail_goods.setVisibility(View.VISIBLE);
            OrderDetailGoodAdapter adapter = new OrderDetailGoodAdapter(order_parcel, orderDetailActivity.orderItemType);
            adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    OrderGoodBean item = (OrderGoodBean) adapter.getItem(position);
                    switch (view.getId()) {
                        case R.id.tv_orderdetail_track: {
                            getPresenter().getOrderParcelTrackData(item.getId());
                        }
                        break;
                        default:
                            break;
                    }
                }
            });
            rv_orderdetail_goods.setLayoutManager(new LinearLayoutManager(mActivity));
            rv_orderdetail_goods.setAdapter(adapter);
        } else {
            rv_orderdetail_goods.setVisibility(View.GONE);
        }
    }

    protected void setPriceView(RecyclerView recyclerView, LinearLayout ll_ordercheck_totalprice_vessel, TextView tv_ordercheck_totalprice) {
        List<ChargesBean> charges = model.getOrder_charges();
        if (charges != null) {
            Iterator<ChargesBean> iterator = charges.iterator();
            while (iterator.hasNext()) {
                /**
                 * 因为视图分离,所以移除了这个
                 */
                ChargesBean next = iterator.next();
                if (TextUtils.equals(next.getCode(), "total")) {
                    ll_ordercheck_totalprice_vessel.setVisibility(View.VISIBLE);
                    tv_ordercheck_totalprice.setText(next.getText());
                    iterator.remove();
                }
            }
        }
        if (charges != null && charges.size() > 0) {
            recyclerView.setVisibility(View.VISIBLE);
            recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
            OrderCheckPriceAdapter priceAdapter = new OrderCheckPriceAdapter(charges);
            recyclerView.setAdapter(priceAdapter);
        }
    }

    /**
     * 账单下载
     *
     * @param tv_orderdetail_viewiransaction
     */
    protected void setViewTransactionView(TextView tv_orderdetail_viewiransaction) {
        if (model != null) {
            List<OrderDetailModel.TransactionDataBean> transaction_data = model.getTransaction_data();
            if (transaction_data != null && transaction_data.size() > 0) {
                tv_orderdetail_viewiransaction.setVisibility(View.VISIBLE);
                tv_orderdetail_viewiransaction.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
                tv_orderdetail_viewiransaction.setOnClickListener(v -> {
                    downPdf();
                });
            }
        }
    }

    @Override
    protected void initData() {
        getPresenter().getOrderDetail(order_id);
    }

    @Override
    protected void initEvent() {

    }



    protected void downPdf() {

        CrashHelper.sceneTag(CrashHelper.OrderDetailActivity_Download_Pdf);
        if (model != null) {
            List<OrderDetailModel.TransactionDataBean> transaction_data = model.getTransaction_data();
            if (transaction_data != null && transaction_data.size() > 0) {
                List<BaseHisModel> list = new ArrayList<>();
                for (OrderDetailModel.TransactionDataBean transaction_datum : transaction_data) {
                    BaseHisModel model = new BaseHisModel() {
                        @Override
                        public int getItemType() {
                            return 0;
                        }
                    };
                    String date = "";
                    if (transaction_datum.getTransaction_date() != null) {
                        date = transaction_datum.getTransaction_date();
                    }
                    model.setCreated_at(date);
                    model.setReference_number(transaction_datum.getReference_number());
                    model.setPdf_download_path(transaction_datum.getPdf_download_path());
                    model.setReceipt_image_path(transaction_datum.getReceipt_image_path());
                    list.add(model);
                }
//                        DownPdfDialog dialog = new DownPdfDialog(this);
//                        dialog.show();
//                        dialog.setDatas(list);
//                Bundle bundle = new Bundle();
//                bundle.putSerializable("datas", (Serializable) list);
                DownPdfDF pdfDF = (DownPdfDF) BaseSimpleFragment.sNewStance(mActivity, DownPdfDF.class);
                pdfDF.mDatas.addAll(list);
                pdfDF.downpdf_title=getString(R.string.transhistory_downloadtitle_order);
                pdfDF.show(getChildFragmentManager(), "DownPdfDF");
            }
        } else {
            CrashHelper.postCatchedException(new Throwable("pdf下载地址是空的"));
        }

    }


    @Override
    public void getOrderDetailResult(ResultModel<OrderDetailModel> orderDetailModelResultModel) {
        if (orderDetailModelResultModel.isSuccess()) {
            model = orderDetailModelResultModel.getData();
            setOrderDetailView();
        }
    }

    @Override
    public void getOrderTrackDataResult(ResultModel<List<OrderTrackModel>> listResultModel) {
//        listResultModel.setResult(1);
        List<OrderTrackModel> list = new ArrayList<>();
        if (listResultModel.isSuccess()) {
            List<OrderTrackModel> data = listResultModel.getData();
//            if (GlobalValue.isDebug && false) {
//                data = new ArrayList<>();
//
//                for (int i = 0; i < 50; i++) {
//                    OrderTrackModel orderTrackModel = new OrderTrackModel();
//                    orderTrackModel.setBatch("EC1800404");
//                    List<OrderTrackModel.DataBean> beans = new ArrayList<>();
//
//                    for (int j = 0; j < 5; j++) {
//                        OrderTrackModel.DataBean bean = new OrderTrackModel.DataBean();
//                        bean.setContext("预计抵达日期");
//                        bean.setDate("2018-08-24");
//                        beans.add(bean);
//                    }
//                    orderTrackModel.setData(beans);
//                    data.add(orderTrackModel);
//                }
//            }
            if (data != null) {
                list.addAll(data);
            }

        }
        DeliveryNoticeDialog dialog = new DeliveryNoticeDialog(mActivity);
        dialog.show();
        dialog.setDatas(list);
    }

    @Override
    public void getOrderParcelTrackDataResult(ResultModel<OrderParcelResModel> resModelResultModel) {
        List<OrderParcelResModel.DataBean> list = new ArrayList<>();
        if (resModelResultModel != null && resModelResultModel.isSuccess()) {
            OrderParcelResModel orderParcelResModel = resModelResultModel.getData();
            if (orderParcelResModel != null && orderParcelResModel.getData() != null) {
                list.addAll(orderParcelResModel.getData());
            }
        }
        InternationalNoticeDialog dialog = new InternationalNoticeDialog(mActivity);
        dialog.show();
        dialog.setOrderParcelResModel(resModelResultModel.getData());
    }

    @Override
    public void button_orderResult(ResultModel resultModel, Map<String, Object> map) {
        if (resultModel.isSuccess()) {
            ToastUtil.showToast(resultModel.getMsg());
            EventBus.getDefault().post(new OrderReceiveEvent());
            getActivity().finish();
        }
    }
}